package Controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/patrickmn/go-cache"
	"net/http"
	"smartHomeNode/v1/base"
)

type MainController struct {
	BaseController
}

/**
 * 获取首页温度信息
 */
func (ctx *MainController) IndexTemp(c *gin.Context) {
	c.JSON(http.StatusOK, ctx.GoSuccess(ctx.GetTempStatus(), ctx.GetDeviceAlias()))
}

/**
 * 获取温度图表数据
 */
func (ctx *MainController) ChartTemp(c *gin.Context) {
	name := c.Query("name")
	filePath := SENSORSFILE + "Temp/" + name + "/"
	data := [7]string{"0", "0", "0", "0", "0", "0", "0"}
	if ctx.CheckDir(filePath) {
		for i := 0; i < 7; i++ {
			fileName := filePath + fmt.Sprintf("%v", i)
			if ctx.CheckFile(fileName) {
				data[i] = ctx.ReadFile(fileName)
			}
		}
	}
	c.JSON(http.StatusOK, ctx.GoSuccess(data, ""))
}

/**
 * 获取温度图表数据
 */
func (ctx *MainController) ChartHum(c *gin.Context) {
	name := c.Query("name")
	filePath := SENSORSFILE + "Hum/" + name + "/"
	data := [7]string{"0", "0", "0", "0", "0", "0", "0"}
	if ctx.CheckDir(filePath) {
		for i := 0; i < 7; i++ {
			fileName := filePath + fmt.Sprintf("%v", i)
			if ctx.CheckFile(fileName) {
				data[i] = ctx.ReadFile(fileName)
			}
		}
	}
	c.JSON(http.StatusOK, ctx.GoSuccess(data, ""))
}

/**
 * 获取首页湿度信息
 */
func (ctx *MainController) IndexHum(c *gin.Context) {
	c.JSON(http.StatusOK, ctx.GoSuccess(ctx.GetHumStatus(), ctx.GetDeviceAlias()))
}

/**
 * 更新方法
 */
func (ctx *MainController) Update(c *gin.Context) {
	json := make(map[string]interface{})
	c.BindJSON(&json)
	name := json["name"]
	color := json["color"]
	alias := json["alias"]
	base.DeviceAlias.Set(fmt.Sprintf("%v", name), fmt.Sprintf("%v", alias)+":"+fmt.Sprintf("%v", color), cache.DefaultExpiration)
	c.JSON(http.StatusOK, ctx.GoSuccess("", ""))
}
